package com.wolfeyes.framework.springsecurity.handle;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.wolfeyes.common.constant.HttpStatusConstants;
import com.wolfeyes.common.response.ResponseResult;
import com.wolfeyes.common.utils.network.web.ResponseUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @description SpringSecurity安全认证权限框架
 * @description 登录成功后权限拒绝（权限不足等）处理类,登录成功后（权限不足等）会调用里面的方法
 * @description 登录后没有权限（权限不足等）等情况下,被拒绝访问时会调用的处理类
 * @see Talk is cheap, Show me the code. -- Linus Torvalds
 * @title 自定义的登录（失败）处理器
 * @author yanyljava
 * @create 2022-01-14 20:56
 */
@Slf4j
@Component
public class CustomizeAccessDeniedHandler implements AccessDeniedHandler {

	/**
	 * @title 登录后权限拒绝处理逻辑
	 * @description 登录后，访问缺失权限的资源会调用
	 * @description 当认证成功的用户访问受保护的资源，但权限不够，则会进入这个处理器
	 * @param httpServletRequest 请求
	 * @param httpServletResponse 响应
	 * @param accessDeniedException 登录后（权限不足）拒绝访问异常
	 * @throws IOException IO异常
	 * @throws ServletException Servlet异常
	 */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException accessDeniedException) throws IOException, ServletException {
    	
    	log.debug("自定义的登录失败处理器被调用 Start！");
    	// 403 访问受限，授权过期（无权限访问，登录后（权限不足）拒绝访问）
    	//int code = HttpStatusConstants.FORBIDDEN;
    	//认证通过，但没权限（权限不足）
    	ResponseResult responseResult = ResponseResult.error(HttpStatusConstants.FORBIDDEN, "访问受限，授权过期或权限不足");
    	httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //httpServletResponse.getWriter().write(JSON.toJSONString(responseResult));
        ResponseUtils.out(responseResult);
        log.debug("自定义的登录失败处理器被调用 End！");
    }
}


